var ajax = require('../../utils/ajax.js');
var app = getApp();
var curPage;
var curScope;
var _onSearch;

function init({
  page,
  scope,
  onSearch
}) {
  curPage = page;
  curScope = scope || 'search';
  _onSearch = onSearch;

  _setData({
    q: '',
    isClear: false,
  })

  curPage['search.input'] = input;
  curPage['search.blur'] = blur;
  curPage['search.focus'] = focus;
  curPage['search.clear'] = clear;
  curPage['search.search'] = search;
  curPage['search.gotoSearchPage'] = gotoSearchPage;
}

function input(evt) {
  var val = evt.detail.value;
  var isClear = !!val;

  _setData({
    q: evt.detail.value,
    isClear,
  })
}

function blur(evt) {
  var val = evt.detail.value;

  if (!val) {
    _setData({
      isClear: false
    });
  }
}

function focus(evt) {
  _setData({
    isClear: true
  });
}

function clear() {
  _setData({
    q: '',
    isClear: false
  });
}

function search(evt) {
  _onSearch && _onSearch(evt.detail.value);
}

function _setData(data) {
  var obj = _getData();

  Object.assign(obj, data);

  curPage.setData({
    [`${curScope}`]: obj
  });
}

function gotoSearchPage() {
  wx.navigateTo({
    url: '/pages/cityInfoList/cityInfoList?from=search'
  });
}

function _getData(key) {
  var data = curPage.data[`${curScope}`] || {};

  if (!key) {
    return data;
  } else {
    return data[key];
  }
}

module.exports = {
  init: init,
};